package com.zaofan.service;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.zaofan.bean.Account;
import com.zaofan.bean.AccountLog;
import com.zaofan.bean.Comment;
import com.zaofan.bean.Goods;
import com.zaofan.bean.GoodsOrderDetail;
import com.zaofan.bean.GoodsOrderInfo;
import com.zaofan.bean.OrderPay;
import com.zaofan.bean.Reply;
import com.zaofan.constant.StateConstant;
import com.zaofan.constant.TypeConstant;
import com.zaofan.constant.UrlConstant;
import com.zaofan.dao.GoodsOrderInfoDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.mobile.bean.GoodsUserOrder;
import com.zaofan.mobile.bean.GoodsUserOrderItem;
import com.zaofan.mobile.bean.PayBean;
import com.zaofan.mobile.bean.SubmitGoodsItem;
import com.zaofan.mobile.bean.SubmitGoodsOrder;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.PayUtils;
import com.zaofan.utils.SqlBuilderUtils;
import com.zaofan.utils.WebUtils;

public class GoodsOrderInfoService {
	private GoodsOrderInfoDao orderInfoDao = new GoodsOrderInfoDao();

	private AccountService accountService = new AccountService();
	private AddressService addressService = new AddressService();

	private GoodsService productService = new GoodsService();

	private CommentService commentService = new CommentService();
	private ReplyService replyService = new ReplyService();
	private GoodsOrderDetailService orderDetailService = new GoodsOrderDetailService();

	public void delete(GoodsOrderInfo orderInfo) {
		orderInfoDao.del(orderInfo);
	}

	public void add(GoodsOrderInfo orderInfo) {
		orderInfoDao.add(orderInfo);
	}

	public void update(GoodsOrderInfo orderInfo) {
		orderInfoDao.update(orderInfo);
	}

	public List<GoodsOrderInfo> findAll(Map<String, Object> params) {
		List<GoodsOrderInfo> data = orderInfoDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return orderInfoDao.count(params);
	}

	public GoodsOrderInfo findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return orderInfoDao.findOne(params);
	}

	public PayBean submitOrder(String orderInfo) throws ServiceException {
		PayBean payBean = new PayBean();
		try {
			Gson gson = new Gson();
			SubmitGoodsOrder submitOrder = gson.fromJson(orderInfo, new TypeToken<SubmitGoodsOrder>() {
			}.getType());
			int userId = submitOrder.getUserId();
			Account account = accountService.findById(userId);
			if (account == null) {
				throw new ServiceException("账户信息有误!!");
			}
			// Address address =
			// addressService.findById(submitOrder.getAddress());
			// if (address == null) {
			// throw new ServiceException("账户收货信息有误!!");
			// }
			if (WebUtils.isEmpty(submitOrder.getSignName())) {
				throw new ServiceException("请填写正确的收货人信息!!");
			}
			if (WebUtils.isEmpty(submitOrder.getMobile())) {
				throw new ServiceException("请填写正确的联系信息!!");
			}
			if (WebUtils.isEmpty(submitOrder.getAddressName())) {
				throw new ServiceException("请填写正确的收收货地址!!");
			}
			List<SubmitGoodsItem> shopData = submitOrder.getShopData();
			if (shopData == null) {
				throw new ServiceException("订单信息有误!!");
			}
			Connection connection = C3p0DataSourceUtils.getConnection();
			QueryRunner runner = new QueryRunner();
			String sql = "";
			try {
				connection.setAutoCommit(false);
				BigDecimal totalPrice = new BigDecimal(0);
				int totalCount = 0;
				BigDecimal freePrice = new BigDecimal(0);
				GoodsOrderInfo order = new GoodsOrderInfo();
				order.setAccountId(account.getId());
				order.setAccountMobile(account.getMobile());
				order.setAreaId(0);
				order.setDeviceId(account.getDeviceId());
				order.setAreaName("");
				order.setBuilderId(0);
				order.setBuilderName("");
				order.setCityId(0);
				order.setCityName("");
				order.setConsignee(submitOrder.getSignName());
				order.setDetail(submitOrder.getAddressName());
				order.setFloorNo("");
				order.setUserMobile(submitOrder.getMobile());
				order.setOrderTime(new Date());
				order.setPayState(StateConstant.ORDER_PAY_STATE_UN_PAY);
				order.setRemark(submitOrder.getMark());
				order.setState(StateConstant.ORDER_STATE_ORDER);
				order.setPlatform(account.getPlatform());
				order.setPayFree(new BigDecimal(0));
				order.setFreePrice(new BigDecimal(0));
				order.setIsActivity(0);

				order.setOrderNo("G" + WebUtils.getOrderId(account.getId()));

				List<GoodsOrderDetail> orderDetails = new ArrayList<>();
				GoodsOrderDetail orderDetail = null;
				for (SubmitGoodsItem item : shopData) {
					orderDetail = new GoodsOrderDetail();
					Integer productId = item.getGoodId();
					Goods product = productService.findById(productId);
					if (product == null) {
						throw new ServiceException("产品信息有误!!");
					}
					if (product.getCount() > 0) {
						if (product.getDateCount() + item.getGoodAccount() > product.getCount()) {
							throw new ServiceException("产品:" + product.getName() + "当天已售完,请明天抓紧下手哦!!");
						}
					}
					orderDetail.setTypeId(product.getType());
					orderDetail.setTypeName(product.getTypeName());
					orderDetail.setProductCount(item.getGoodAccount());
					orderDetail.setProductId(productId);
					orderDetail.setProductImage(product.getImage());
					orderDetail.setOrderNo(order.getOrderNo());
					String productName = product.getName();
					BigDecimal price = product.getPrice();
					totalCount += item.getGoodAccount();
					orderDetail.setProductName(productName);
					orderDetail.setProductPrice(price);
					orderDetail.setTotalPrice(orderDetail.getProductPrice().multiply(new BigDecimal(item.getGoodAccount())));
					orderDetail.setFree(new BigDecimal(0));
					orderDetails.add(orderDetail);
					totalPrice = totalPrice.add(orderDetail.getTotalPrice());
				}
				String activityIds = "";
				String activityName = "";
				order.setPayPrice(totalPrice.subtract(freePrice));
				order.setQuantity(totalCount);
				order.setTotalPrice(totalPrice);
				order.setFreePrice(freePrice);
				if (!"".equals(activityIds)) {
					activityIds = activityIds.substring(0, activityIds.length() - 1);
				}
				if (!"".equals(activityName)) {
					activityName = activityName.substring(0, activityName.length() - 1);
				}
				order.setActivityIds(activityIds);
				order.setActivityName(activityName);
				sql = SqlBuilderUtils.builderInsertSql(GoodsOrderInfo.class, order);
				System.err.println(sql);

				runner.update(connection, sql);
				int orderId = 0;
				// 获取新增记录的自增主键
				try {
					Long id = (Long) runner.query(connection, "SELECT LAST_INSERT_ID()", new ScalarHandler<Long>());
					orderId = id.intValue();
				} catch (Exception e) {
					BigInteger id = (BigInteger) runner.query(connection, "SELECT LAST_INSERT_ID()",
							new ScalarHandler<BigInteger>());
					orderId = id.intValue();
				}
				for (GoodsOrderDetail detail : orderDetails) {
					detail.setOrderId(orderId);
					sql = SqlBuilderUtils.builderInsertSql(GoodsOrderDetail.class, detail);
					System.err.println(sql);
					runner.update(connection, sql);
				}
				payBean.setOrderId(orderId);
				payBean.setOrderNo(order.getOrderNo());
				payBean.setOrderTime(order.getOrderTime());
				payBean.setAccountMoney(account.getMoney());

/*商城订单不支持余额支付
 * 				if (account.getMoney() >= (totalPrice - freePrice)) {
					payBean.setAlipay(PayUtils.getAlipayGoodsString(payBean.getOrderNo(), "早范", "早范订单结算",
							totalPrice - freePrice));
					payBean.setWeiPay(
							PayUtils.getWeiPayGoods(payBean.getOrderNo(), "早范", "早范订单结算", totalPrice - freePrice));
				} else {
					if (account.getMoney() > 0) {
						payBean.setAlipay(PayUtils.getAlipayGoodsString(payBean.getOrderNo(), "早范", "早范订单结算",
								totalPrice - freePrice - account.getMoney()));
						payBean.setWeiPay(PayUtils.getWeiPayGoods(payBean.getOrderNo(), "早范", "早范订单结算",
								totalPrice - freePrice - account.getMoney()));
					} else {
						payBean.setAlipay(PayUtils.getAlipayGoodsString(payBean.getOrderNo(), "早范", "早范订单结算",
								totalPrice - freePrice));
						payBean.setWeiPay(
								PayUtils.getWeiPayGoods(payBean.getOrderNo(), "早范", "早范订单结算", totalPrice - freePrice));
					}
				}*/
				payBean.setAlipay(PayUtils.getAlipayGoodsString(payBean.getOrderNo(), "早范", "早范订单结算", totalPrice.subtract(freePrice)));
				payBean.setWeiPay(PayUtils.getWeiPayGoods(payBean.getOrderNo(), "早范", "早范订单结算", totalPrice.subtract(freePrice)));
				payBean.setFreePrice(freePrice);
				payBean.setGoodsCount(totalCount);
				payBean.setTotalPrice(totalPrice);
				// account.setBuilderId(address.getBuilderId());
				// account.setBuilderName(address.getBuilderName());
				// account.setCityId(address.getCityId());
				// account.setCityName(address.getCityName());
				sql = SqlBuilderUtils.builderUpdateSql(Account.class, account);
				System.err.println(sql);
				runner.update(connection, sql);
				connection.commit();
			} catch (ServiceException e) {
				connection.rollback();
				throw e;
			} catch (Exception e) {
				connection.rollback();
				e.printStackTrace();
				throw e;
			} finally {
				connection.close();
			}
		} catch (JsonSyntaxException e) {
			throw new ServiceException("订单信息有误!!");
		} catch (ServiceException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("订单信息有误!!");
		}
		return payBean;

	}

	public List<GoodsUserOrder> findByAcccountId(Integer accountId, Integer begin, Integer end) {
		List<GoodsUserOrder> orders = new ArrayList<>();
		List<GoodsOrderInfo> orderInfos = orderInfoDao.findByAcccountId(accountId, begin, end);
		for (GoodsOrderInfo info : orderInfos) {
			GoodsUserOrder order = dealOrder(info);
			if (order != null) {
				orders.add(order);
			}
		}
		return orders;
	}

	public void deleteByOrderId(Integer orderId) throws ServiceException, SQLException {
		GoodsOrderInfo info = orderInfoDao.findById(orderId);
		if (info == null) {
			throw new ServiceException("订单数据错误!!");
		}
		// 普通订单删除
		if (info.getState() == StateConstant.ORDER_STATE_ORDER
				&& info.getState() == StateConstant.ORDER_PAY_STATE_UN_PAY) {
			Connection connection = C3p0DataSourceUtils.getConnection();
			connection.setAutoCommit(false);
			try {
				String sql = SqlBuilderUtils.builderDelSql(GoodsOrderInfo.class, info);
				QueryRunner runner = new QueryRunner();
				runner.update(connection, sql);
				sql = "delete FROM " + GoodsOrderDetail.class.getSimpleName().toLowerCase() + " where orderId = "
						+ orderId;
				runner.update(connection, sql);
				connection.commit();
			} catch (Exception e) {
				e.printStackTrace();
				connection.rollback();
			} finally {
				connection.close();
			}
		} else {
			throw new ServiceException("订单无法删除!!");
		}

	}

	public GoodsUserOrder getOrderInfo(Integer orderId)
			throws ServiceException, IllegalAccessException, InvocationTargetException {
		GoodsOrderInfo info = orderInfoDao.findById(orderId);
		if (info == null) {
			throw new ServiceException("订单数据有误!!");
		}
		GoodsUserOrder order = dealOrder(info);
		if (order.getState() == StateConstant.ORDER_STATE_COMMENT) {
			Comment comment = commentService.findByOrderId(order.getId());
			com.zaofan.mobile.bean.Comment data = new com.zaofan.mobile.bean.Comment();
			BeanUtils.copyProperties(data, comment);
			if (comment.getIsReply() == 1) {
				Reply reply = replyService.findByCommentId(comment.getId());
				data.setReply(reply);
			}
			if (comment.getUserPhoto() != null && !"".equals(comment.getUserPhoto())) {
				data.setUserPhoto(UrlConstant.HOST_URL + comment.getUserPhoto());
			}
			order.setComment(data);

		}
		return order;
	}

	public GoodsUserOrder dealOrder(GoodsOrderInfo info) {
		GoodsUserOrder order = null;
		try {
			order = new GoodsUserOrder();
			List<GoodsUserOrderItem> orderItem;
			GoodsUserOrderItem item = null;
			BeanUtils.copyProperties(order, info);
			order.setDetail(info.getDetail());
			List<GoodsOrderDetail> orderDetails = orderDetailService.findByOrderId(order.getId());
			if (orderDetails != null && orderDetails.size() > 0) {
				orderItem = new ArrayList<>();
				for (GoodsOrderDetail detail : orderDetails) {
					item = new GoodsUserOrderItem();
					BeanUtils.copyProperties(item, detail);
					item.setProductImage(UrlConstant.HOST_URL + detail.getProductImage());
					orderItem.add(item);
				}
				order.setGoods(orderItem);
			} else {
				order.setGoods(new ArrayList<GoodsUserOrderItem>());
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return order;
	}

	public void addOrderComment(Comment comment) throws ServiceException, SQLException {
		if (comment.getContent() == null || "".equals(comment.getContent())) {
			throw new ServiceException("请填写评价内容!!");
		}
		if (comment.getOrderId() == 0) {
			throw new ServiceException("订单数据有误!!");
		}
		GoodsOrderInfo orderInfo = findById(comment.getOrderId());
		if (orderInfo == null) {
			throw new ServiceException("订单数据有误!!");
		}
		if (orderInfo.getPayState() == StateConstant.ORDER_PAY_STATE_UN_PAY
				|| orderInfo.getPayState() == StateConstant.ORDER_PAY_STATE_PAY_CHECK
				|| orderInfo.getState() == StateConstant.ORDER_STATE_ORDER
				|| orderInfo.getState() == StateConstant.ORDER_STATE_COMMENT) {
			throw new ServiceException("该订单暂时无法进行评论!!");
		}
		comment.setOrderNo(orderInfo.getOrderNo());
		comment.setOrderTime(orderInfo.getOrderTime());
		Account account = accountService.findById(comment.getAccountId());
		if (account == null) {
			throw new ServiceException("用户信息有误!!");
		}
		if (orderInfo.getAccountId() != account.getId()) {
			throw new ServiceException("订单与用户匹配有误!!");
		}

		comment.setAccountMobile(account.getMobile());
		comment.setIsReply(0);
		comment.setAve((comment.getTasteScore() + comment.getSpeedScore()) / 2);
		if (comment.getAve() < 3) {
			comment.setCommentType("差评");
			// 发送 推送到管理平台 提示管理处理
		} else if (comment.getAve() == 3) {
			comment.setCommentType("中评");
			// 发送 推送到管理平台 提示管理处理
		} else {
			comment.setCommentType("好评");
		}
		comment.setAddTime(new Date());
		comment.setNickName(account.getNickname());
		comment.setUserPhoto(account.getPhoto());
		Connection connection = C3p0DataSourceUtils.getConnection();
		connection.setAutoCommit(false);
		try {
			QueryRunner runner = new QueryRunner();
			String sql = "";
			sql = SqlBuilderUtils.builderInsertSql(Comment.class, comment);
			System.err.println(sql);
			runner.update(connection, sql);
			orderInfo.setState(StateConstant.ORDER_STATE_COMMENT);
			sql = "update " + GoodsOrderInfo.class.getSimpleName().toLowerCase() + " set state = "
					+ StateConstant.ORDER_STATE_COMMENT + " where orderNo = '" + orderInfo.getOrderNo() + "'";
			runner.update(connection, sql);
			connection.commit();
		} catch (Exception e) {
			e.printStackTrace();
			connection.rollback();
		} finally {
			connection.close();
		}
	}

	public GoodsOrderInfo findByOrderNo(String orderNo) {
		Map<String, Object> params = new HashMap<>();
		params.put("orderNo", orderNo);
		return orderInfoDao.findOne(params);
	}

	public void updateOrderPayState(String orderNo) throws ServiceException {
		if (orderNo == null) {
			throw new ServiceException("订单信息有误!!");
		}
		GoodsOrderInfo info = findByOrderNo(orderNo);
		if (info == null) {
			throw new ServiceException("订单信息有误!!");
		}
		orderInfoDao.updateaOrderPayState(orderNo);
	}

	public void payOrderByAccountMoney(String orderNo) throws ServiceException, SQLException {
		GoodsOrderInfo order = findByOrderNo(orderNo);
		if (order == null) {
			throw new ServiceException("订单信息错误!!");
		}
		Account account = accountService.findById(order.getAccountId());
		if (account == null) {
			throw new ServiceException("账户信息错误!!");
		}
		if (account.getMoney().compareTo((order.getTotalPrice().subtract(order.getFreePrice()))) < 0) {
			throw new ServiceException("账户余额不足!!");
		}
		Connection connection = C3p0DataSourceUtils.getConnection();
		try {
			connection.setAutoCommit(false);
			// 更新订单状态
			String sql = "update " + GoodsOrderInfo.class.getSimpleName().toLowerCase() + " set payState = "
					+ StateConstant.ORDER_PAY_STATE_PAY + ",state = " + StateConstant.ORDER_STATE_PAY
					+ ",payType='余额支付' where orderNo = '" + order.getOrderNo() + "'";
			QueryRunner runner = new QueryRunner();
			runner.update(connection, sql);
			// 增加订单支付记录
			OrderPay orderPay = new OrderPay();
			orderPay.setAddTime(new Date());
			orderPay.setOrderId(order.getId());
			orderPay.setOrderNo(order.getOrderNo());
			orderPay.setTradeNo(order.getOrderNo());
			orderPay.setPayMethod("账户余额支付");
			orderPay.setPayPrice(order.getPayPrice());
			orderPay.setPayState("支付成功");
			orderPay.setRemark("账户余额支付");
			sql = SqlBuilderUtils.builderInsertSql(OrderPay.class, orderPay);
			runner.update(connection, sql);
			// 增加用户账户记录
			AccountLog accountLog = new AccountLog();
			accountLog.setAccountId(account.getId());
			accountLog.setAccountMobile(account.getMobile());
			accountLog.setAddTime(new Date());
			accountLog.setMark("余额支付");
			accountLog.setType(TypeConstant.log_type_yu_er_pay);
			accountLog.setMoney(order.getPayPrice());
			accountLog.setBeforeMoney(account.getMoney());
			accountLog.setAfterMoney(account.getMoney().subtract(order.getPayPrice()));
			sql = SqlBuilderUtils.builderInsertSql(AccountLog.class, accountLog);
			runner.update(connection, sql);
			account.setMoney(account.getMoney().subtract(order.getPayPrice()));
			sql = SqlBuilderUtils.builderUpdateSql(Account.class, account);
			runner.update(connection, sql);
			connection.commit();
		} catch (Exception e) {
			connection.rollback();
		} finally {
			connection.close();
		}
	}

	public List<GoodsOrderInfo> findAllOrder(Map<String, Object> params) {
		List<GoodsOrderInfo> orderInfos = findAll(params);
		return orderInfos;
	}

	// public List<GoodsOrderInfo> exportTodaySendUserMobile() {
	// Calendar calendar = Calendar.getInstance();
	// int year = calendar.get(Calendar.YEAR);
	// int month = calendar.get(Calendar.MONTH) + 1;
	// int day = calendar.get(Calendar.DAY_OF_MONTH);
	// try {
	// String sql = "select * from " +
	// GoodsOrderInfo.class.getSimpleName().toLowerCase() + " where sendDate =
	// '"
	// + year + "-" + (month < 9 ? "0" + month : month + "") + "-" + (day < 9 ?
	// "0" + day : day + "")
	// + "' and state in (" + StateConstant.ORDER_STATE_COMMENT + "," +
	// StateConstant.ORDER_STATE_PAY
	// + ") and payState in ( " + StateConstant.ORDER_PAY_STATE_PAY + ","
	// + StateConstant.ORDER_PAY_STATE_ARCHIVE + ")" + " and isMuti = 0 group by
	// accountMobile";
	// System.err.println(sql);
	// QueryRunner runner = new
	// QueryRunner(C3p0DataSourceUtils.getDataSource());
	// return runner.query(sql, new BeanListHandler<>(GoodsOrderInfo.class));
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// return Collections.EMPTY_LIST;
	// }

	// public List<ProductList> findTomorrowListBySendData(String sendDate) {
	// try {
	// String sql = "select o.orderNo,o.id as
	// orderId,d.productId,d.productName,sum(d.productCount) as
	// productCount,d.shopName,d.shopId,d.productPrice from orderinfo
	// o,orderdetail d where o.isMuti = 0 and o.id = d.orderId and o.payState in
	// (2,3) and sendDate = '"
	// + sendDate + "' group by d.productName";
	// System.err.println(sql);
	// QueryRunner runner = new
	// QueryRunner(C3p0DataSourceUtils.getDataSource());
	// return runner.query(sql, new BeanListHandler<>(ProductList.class));
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// return null;
	// }

	public PayBean submitOrderByOrderId(String orderId) throws ServiceException {
		Integer id = 0;
		try {
			id = Integer.valueOf(orderId);
		} catch (Exception e) {
			throw new ServiceException("订单信息有误,请刷新试试!!");
		}
		PayBean payBean = new PayBean();
		GoodsOrderInfo order = findById(id);
		if (order == null) {
			throw new ServiceException("订单信息有误,请刷新试试!!");
		}
		if (order.getState() != StateConstant.ORDER_STATE_ORDER
				|| order.getPayState() != StateConstant.ORDER_PAY_STATE_UN_PAY) {
			throw new ServiceException("订单已经支付,无法重新支付!!");
		}
		Account account = accountService.findById(order.getAccountId());
		if (account == null) {
			throw new ServiceException("订单信息有误!!");
		}
		payBean.setOrderId(id);
		payBean.setOrderNo(order.getOrderNo());
		payBean.setOrderTime(order.getOrderTime());
		payBean.setAccountMoney(account.getMoney());

/* 商城不支持余额
 * 		if (account.getMoney() >= (order.getPayPrice())) {
			payBean.setAlipay(PayUtils.getAlipayGoodsString(payBean.getOrderNo(), "早范", "早范订单结算", order.getPayPrice()));
			payBean.setWeiPay(PayUtils.getWeiPayGoods(payBean.getOrderNo(), "早范", "早范订单结算", order.getPayPrice()));
		} else {
			if (account.getMoney() > 0) {
				payBean.setAlipay(PayUtils.getAlipayGoodsString(payBean.getOrderNo(), "早范", "早范订单结算",
						order.getPayPrice() - account.getMoney()));
				payBean.setWeiPay(PayUtils.getWeiPayGoods(payBean.getOrderNo(), "早范", "早范订单结算",
						order.getPayPrice() - account.getMoney()));
			} else {
				payBean.setAlipay(
						PayUtils.getAlipayGoodsString(payBean.getOrderNo(), "早范", "早范订单结算", order.getPayPrice()));
				payBean.setWeiPay(PayUtils.getWeiPayGoods(payBean.getOrderNo(), "早范", "早范订单结算", order.getPayPrice()));
			}
		}*/
		payBean.setAlipay(PayUtils.getAlipayGoodsString(payBean.getOrderNo(), "早范", "早范订单结算", order.getPayPrice()));
		payBean.setWeiPay(PayUtils.getWeiPayGoods(payBean.getOrderNo(), "早范", "早范订单结算", order.getPayPrice()));
		payBean.setFreePrice(order.getFreePrice());
		payBean.setGoodsCount(order.getQuantity());
		payBean.setTotalPrice(order.getTotalPrice());
		return payBean;
	}

	// public List<OrderInfo> exportTomorrowSendUserPhone() {
	// Calendar calendar = Calendar.getInstance();
	// calendar.add(Calendar.DATE, 1);
	// int year = calendar.get(Calendar.YEAR);
	// int month = calendar.get(Calendar.MONTH) + 1;
	// int day = calendar.get(Calendar.DAY_OF_MONTH);
	// try {
	// String sql = "select * from " +
	// OrderInfo.class.getSimpleName().toLowerCase() + " where sendDate = '" +
	// year
	// + "-" + (month < 9 ? "0" + month : month + "") + "-" + (day < 9 ? "0" +
	// day : day + "")
	// + "' and state in (" + StateConstant.ORDER_STATE_COMMENT + "," +
	// StateConstant.ORDER_STATE_PAY
	// + ") and payState in ( " + StateConstant.ORDER_PAY_STATE_PAY + ","
	// + StateConstant.ORDER_PAY_STATE_ARCHIVE + ")" + " and isMuti = 0 group by
	// accountMobile";
	// System.err.println(sql);
	// QueryRunner runner = new
	// QueryRunner(C3p0DataSourceUtils.getDataSource());
	// return runner.query(sql, new BeanListHandler<>(OrderInfo.class));
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// return Collections.EMPTY_LIST;
	// }

	public void updateWithOutPay(long time) {
		String sql = "update " + GoodsOrderInfo.class.getSimpleName().toLowerCase() + " set isTimeOut = 1 where "
				+ " state = " + StateConstant.ORDER_STATE_ORDER + " and payState = "
				+ StateConstant.ORDER_PAY_STATE_UN_PAY + " and UNIX_TIMESTAMP(now())-UNIX_TIMESTAMP(orderTime) >= "
				+ time;
		System.err.println(sql);
		QueryRunner runner = new QueryRunner(C3p0DataSourceUtils.getDataSource());
		try {
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void payOrderByAdminMoney(String orderNo) throws ServiceException, SQLException {
		GoodsOrderInfo order = findByOrderNo(orderNo);
		if (order == null) {
			throw new ServiceException("订单信息错误!!");
		}
		Connection connection = C3p0DataSourceUtils.getConnection();
		try {
			connection.setAutoCommit(false);
			// 更新订单状态
			String sql = "update " + GoodsOrderInfo.class.getSimpleName().toLowerCase() + " set payState = "
					+ StateConstant.ORDER_PAY_STATE_PAY + ",state = " + StateConstant.ORDER_STATE_PAY
					+ ",payType='管理员操作支付' where orderNo = '" + order.getOrderNo() + "'";
			QueryRunner runner = new QueryRunner();
			runner.update(connection, sql);
			// 增加订单支付记录
			OrderPay orderPay = new OrderPay();
			orderPay.setAddTime(new Date());
			orderPay.setOrderId(order.getId());
			orderPay.setOrderNo(order.getOrderNo());
			orderPay.setTradeNo(order.getOrderNo());
			orderPay.setPayMethod("管理员操作支付");
			orderPay.setPayPrice(order.getPayPrice());
			orderPay.setPayState("支付成功");
			orderPay.setRemark("管理员操作支付");
			sql = SqlBuilderUtils.builderInsertSql(OrderPay.class, orderPay);
			runner.update(connection, sql);
			connection.commit();
		} catch (Exception e) {
			connection.rollback();
		} finally {
			connection.close();
		}
	}

	// public List<OrderInfo> exportTomorrowSendUserPhoneByShopId(Integer
	// shopId) {
	// Calendar calendar = Calendar.getInstance();
	// calendar.add(Calendar.DATE, 1);
	// int year = calendar.get(Calendar.YEAR);
	// int month = calendar.get(Calendar.MONTH) + 1;
	// int day = calendar.get(Calendar.DAY_OF_MONTH);
	// try {
	// String sql = "select * from " +
	// OrderInfo.class.getSimpleName().toLowerCase() + " where sendDate = '" +
	// year
	// + "-" + (month < 9 ? "0" + month : month + "") + "-" + (day < 9 ? "0" +
	// day : day + "")
	// + "' and state in (" + StateConstant.ORDER_STATE_COMMENT + "," +
	// StateConstant.ORDER_STATE_PAY
	// + ") and payState in ( " + StateConstant.ORDER_PAY_STATE_PAY + ","
	// + StateConstant.ORDER_PAY_STATE_ARCHIVE + ")" + " and isMuti = 0 and
	// shopId = " + shopId
	// + " group by accountMobile";
	// System.err.println(sql);
	// QueryRunner runner = new
	// QueryRunner(C3p0DataSourceUtils.getDataSource());
	// return runner.query(sql, new BeanListHandler<>(OrderInfo.class));
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// return Collections.EMPTY_LIST;
	// }

	// public List<OrderInfo> exportTodaySendUserMobile(Integer shopId) {
	// Calendar calendar = Calendar.getInstance();
	// int year = calendar.get(Calendar.YEAR);
	// int month = calendar.get(Calendar.MONTH) + 1;
	// int day = calendar.get(Calendar.DAY_OF_MONTH);
	// try {
	// String sql = "select * from " +
	// OrderInfo.class.getSimpleName().toLowerCase() + " where sendDate = '" +
	// year
	// + "-" + (month < 9 ? "0" + month : month + "") + "-" + (day < 9 ? "0" +
	// day : day + "")
	// + "' and state in (" + StateConstant.ORDER_STATE_COMMENT + "," +
	// StateConstant.ORDER_STATE_PAY
	// + ") and payState in ( " + StateConstant.ORDER_PAY_STATE_PAY + ","
	// + StateConstant.ORDER_PAY_STATE_ARCHIVE + ")" + " and isMuti = 0 and
	// shopId = " + shopId
	// + " group by accountMobile";
	// System.err.println(sql);
	// QueryRunner runner = new
	// QueryRunner(C3p0DataSourceUtils.getDataSource());
	// return runner.query(sql, new BeanListHandler<>(OrderInfo.class));
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// return Collections.EMPTY_LIST;
	// }

	// public List<ProductList> findTomorrowListBySendData(String sendDate,
	// Integer shopId) {
	// try {
	// String sql = "select o.orderNo,o.id as
	// orderId,d.productId,d.productName,sum(d.productCount) as
	// productCount,d.shopName,d.shopId,d.productPrice from orderinfo
	// o,orderdetail d where o.isMuti = 0 and o.shopId = "
	// + shopId + " and o.id = d.orderId and o.payState in (2,3) and sendDate =
	// '" + sendDate
	// + "' group by d.productId";
	// System.err.println(sql);
	// QueryRunner runner = new
	// QueryRunner(C3p0DataSourceUtils.getDataSource());
	// return runner.query(sql, new BeanListHandler<>(ProductList.class));
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// return null;
	// }

	// public List<ProductList> findOrderTemp() {
	// try {
	// String sql = "select o.orderNo,o.id as
	// orderId,d.productId,d.productName,sum(d.productCount) as
	// productCount,d.shopName,d.shopId,d.productPrice from orderinfo
	// o,orderdetail d where o.isMuti = 0 and o.id = d.orderId and o.payState in
	// (2,3) and date(o.orderTime) >= '2015-12-17' and date(o.orderTime) <=
	// '2015-12-31' and accountMobile != '18016538177' group by d.productId;";
	// System.err.println(sql);
	// QueryRunner runner = new
	// QueryRunner(C3p0DataSourceUtils.getDataSource());
	// return runner.query(sql, new BeanListHandler<>(ProductList.class));
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// return null;
	// }

}
